


import React, { Component } from 'react'
import { connect } from 'react-redux';
import { Breadcrumb, Layout } from 'antd'
import axios from 'axios'
import { Table, Button, Popconfirm, Input, Spin, Modal, Form, Select, DatePicker, Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
const { Search } = Input;
const { Content } = Layout;
const { Option } = Select;


const layout = {
    labelCol: {
        span: 4,
    },
    wrapperCol: {
        span: 20,
    },
};

const tailLayout = {
    wrapperCol: {
        offset: 4,
        span: 20,
    },
};

function mapStateToProps(state) {
    return {
        ...state
    };
}

function mapDispatchToProps(dispatch) {
    return {
        getList() {
            // 即将加载数据 ，设置loading状态为true
            dispatch({ type: "SET_LOADING", data: true });
            axios.get('/api/teacher/list').then((res) => {
                dispatch({ type: "SET_TEACHER_LIST", data: res.data.data });

                // 拿到数据， 设置loading状态为false
                dispatch({ type: "SET_LOADING", data: false });
            })
        },

        //搜索教师
        searchTeacher(keyword) {
            dispatch({ type: "SEARCH_TEACHER", data: keyword });
        },


        //添加教师
        addTeacher(teacher) {
            dispatch({ type: "ADD_TEACHER", data: teacher })
        },

        // 删除教师
        delTeacher(teacher) {
            dispatch({ type: "DEL_TEACHER", data: teacher })
        }
    };
}

class TeacherList extends Component {

    state = { visibleAdd: false, visibleEdit: false, year: "", imgLoading: false, imageUrl: "" };

    formRef = React.createRef();
    formRefEdit= React.createRef();

    componentWillMount() {
        if (this.props.teacher_list.length === 0) {
            this.props.getList();
        }

    }
    render() {
        let columns = [
            {
                title: '姓名',
                dataIndex: 'name'
            },
            {
                title: '头像',
                dataIndex: 'image',
                render: text => {
                    return <img className="profile" src={text} alt="" />
                }

            },
            {
                title: '性别',
                dataIndex: 'gender',

            },

            {
                title: '年龄',
                dataIndex: 'age',

            },

            {
                title: '带班',
                dataIndex: 'clzss',

            },
            {
                title: "加入年份",
                dataIndex: 'year'
            },
            {
                title: '操作',
                render: (text) => {
                    return <div><Button type="link" onClick={
                        () => {
                            this.setState({ visibleAdd: true });
                            console.log('this.formRef',this.formRef);

                          
                        }
                    }>修改</Button>

                        <Popconfirm
                            title={"你是否要删除教师" + text.name + "?"}
                            onConfirm={() => {
                                this.props.delTeacher(text)

                            }}
                            onCancel={() => {

                            }}
                            okText="确定删除"
                            cancelText="算了 ，我再想想"
                        >
                            <Button type="link">删除</Button>
                        </Popconfirm>
                    </div>
                }
            }
        ];
        let { teacher_list } = this.props;
        const { imgLoading, imageUrl } = this.state;
        const uploadButton = (
            <div>
                {imgLoading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>点击上传</div>
            </div>
        );

        // 图片地址转 base64
        function getBase64(img, callback) {
            console.log('img', img);
            const reader = new FileReader();
            reader.addEventListener('load', () => callback(reader.result));
            reader.readAsDataURL(img);
        }


        // 上传图片前校验
        function beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('You can only upload JPG/PNG file!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('Image must smaller than 2MB!');
            }
            return isJpgOrPng && isLt2M;
        }


        // 选择图片之后
        let handleChange = info => {
            if (info.file.status === 'uploading') {
                this.setState({ imgLoading: true });
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                getBase64(info.file.originFileObj, imageUrl =>
                    this.setState({
                        imageUrl,
                        imgLoading: false,
                    }),
                );
            }
        };


        return (
            <div>

                <Breadcrumb style={{ margin: '16px 0' }}>
                    <Breadcrumb.Item>首页</Breadcrumb.Item>
                    <Breadcrumb.Item>教师管理</Breadcrumb.Item>
                    <Breadcrumb.Item>教师列表</Breadcrumb.Item>
                </Breadcrumb>
                <Content
                    className="site-layout-background"
                    style={{
                        padding: 24,
                        margin: 0,
                        minHeight: 280,
                        background: '#fff'
                    }}
                >

                    {this.props.loading}

                    <p>
                        <Button onClick={() => {
                            this.setState({ visibleAdd: true })
                        }}>添加教师</Button>
                        <Search placeholder="请输入关键词" onSearch={value => { this.props.searchTeacher(value) }} enterButton />





                    </p>

                    {/* {教师列表} */}
                    <Spin className={!this.props.loading ? "hidden" : ""} />
                    <Table columns={columns} dataSource={teacher_list}></Table>
                </Content>

                {/* 添加教师弹框 */}
                <Modal
                    destroyOnClose={true}
                    footer={null}
                    title="添加教师"
                    visible={this.state.visibleAdd}
                    onOk={() => {

                    }}
                    onCancel={() => {
                        this.setState({ visibleAdd: false })
                    }}
                >
                    <p>
                        <Form {...layout} ref={this.formRefEdit} name="control-add-ref" onFinish={(values) => {
                            // 提交表单

                            values = { ...values, year: this.state.year, image: this.state.imageUrl };
                            console.log('提交表单 values', values);
                            this.props.addTeacher(values);

                            // 手工清除上次添加教师时上传的图片信息
                            this.setState({ imageUrl: "" });
                            this.setState({ imgLoading: false });
                            // 隐藏modal框
                            this.setState({ visibleAdd: false });
                        }}>
                            <Form.Item
                                name="name"
                                label="姓名"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入姓名"
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item name="yeardate" label="加入年份">



                                <DatePicker onChange={(date, dateString) => {
                                    console.log(date, dateString);
                                    this.setState({ year: dateString })
                                }} picker="year" />

                            </Form.Item>

                            <Form.Item name="img" lable="头像上传">
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                >
                                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                </Upload>
                            </Form.Item>
                            <Form.Item
                                name="gender"
                                label="性别"
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择性别"
                                    },
                                ]}
                            >
                                <Select
                                    placeholder="请选择或者输入"
                                    onChange={(e) => {
                                        console.log('性别选项切换', e)
                                    }}

                                >
                                    <Option value="男">男士</Option>
                                    <Option value="女">女士</Option>

                                </Select>
                            </Form.Item>

                            <Form.Item {...tailLayout}>
                                <Button type="primary" htmlType="submit">
                                    添加教师
          </Button>
                                <Button htmlType="button" onClick={() => {
                                    this.formRef.current.resetFields();
                                }}>
                                    重置
          </Button>

                            </Form.Item>
                        </Form>
                    </p>

                </Modal>
                {/* 修改教师弹框 */}


                <Modal
                    title="修改教师"
                    footer={null}
                    visible={this.state.visibleEdit}
                    onOk={() => {

                    }}
                    onCancel={() => {
                        this.setState({ visibleEdit: false })
                    }}
                >
                    <p>
                        <Form {...layout} ref={this.formRef} name="control-edit-ref" onFinish={(values) => {
                            // 提交表单

                            values = { ...values, year: this.state.year, image: this.state.imageUrl };
                            console.log('提交表单 values', values);
                            this.props.addTeacher(values);

                            // 手工清除上次添加教师时上传的图片信息
                            this.setState({ imageUrl: "" });
                            this.setState({ imgLoading: false });
                            // 隐藏modal框
                            this.setState({ visibleAdd: false });
                        }}>
                            <Form.Item
                                name="name"
                                label="姓名"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入姓名"
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item name="yeardate" label="加入年份">



                                <DatePicker onChange={(date, dateString) => {
                                    console.log(date, dateString);
                                    this.setState({ year: dateString })
                                }} picker="year" />

                            </Form.Item>

                            <Form.Item name="img" lable="头像上传">
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                >
                                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                </Upload>
                            </Form.Item>
                            <Form.Item
                                name="gender"
                                label="性别"
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择性别"
                                    },
                                ]}
                            >
                                <Select
                                    placeholder="请选择或者输入"
                                    onChange={(e) => {
                                        console.log('性别选项切换', e)
                                    }}

                                >
                                    <Option value="男">男士</Option>
                                    <Option value="女">女士</Option>

                                </Select>
                            </Form.Item>

                            <Form.Item {...tailLayout}>
                                <Button type="primary" htmlType="submit">
                                    更新教师
          </Button>
                               
                            </Form.Item>
                        </Form>
                    </p>
                    
                </Modal>

            </div>
        )
    }
}

export default connect(
    mapStateToProps, mapDispatchToProps
)(TeacherList);








